<?php

namespace app\admin\controller\store;

use app\admin\model\house\In;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 仓库入库记录
 *
 * @icon fa fa-circle-o
 */
class Housein extends Backend
{
    
    /**
     * In模型对象
     * @var \app\admin\model\house\In
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\house\In;
        $this->view->assign("typeList", $this->model->getTypeList());
        $admin = Session::get('admin');
        $this->userid = $admin['userid'];
        $this->view->assign("userid", $this->userid);


    }
    public function add()
    {
        $db = new \app\admin\model\Githouse();
        $info = $db->where(array('manger'=>$this->userid))->find();
        $cid = $info['id'];
        if ($this->userid==1){
            $cid=1;
        }else{
            if (!$cid)$this->error("必须是仓库管理员！");
        }


        if ($this->request->isPost()) {
            $params = $this->request->post("shop/a");
            if ($params){
                //查询当前
                //$order_id
                $inDb = new In();
                $order_id = $inDb->getOrderId();
                $type = 7;
                /*
                 * ["id"]=>
                          string(1) "4"
                          ["num"]=>
                          string(1) "1"
                 * */
                $stDb = new \app\admin\model\Stock();

                $preDb = new \app\admin\model\Preproduct();
                $args = $this->request->post("row/a");
                foreach ($params as $k=>$v){
                        //house_in添加记录

                        //库存数量累计
                        //查询当前成品下的半成品组成
                        $infos = $preDb->where(array('id'=>$v['id']))->find();
                        $bcp = explode(',',$infos['bcp']);
                        if ($bcp){
                            $inDb->insert(array(
                                "order_id"=>$order_id,
                                'type'=>$type,
                                'shopid'=>$v['id'],
                                'num'=>$v['num'],
                                'cid'=>$cid,
                                'pur_id'=>0,
                                'inputtime'=>time(),
                                'publisher'=>$this->userid,
                                'mark'=>$args['mark'],
                                'bcp'=>$infos['bcp'],

                            ));
                            foreach ($bcp as $d){
                               $starr = $stDb->where(array('cid'=>$cid,'shopid'=>$d))->find();
                               if ($starr){
                                   //修改
                                    $stDb->where(array('cid'=>$cid,'shopid'=>$d))->setInc('num', $v['num']); ;

                               }else{
                                   $stDb->insert(array(
                                       'cid'=>$cid,
                                       'shopid'=>$d,
                                       'num'=>$v['num']

                                   ));
                                   //添加
                               }
                               //库存表操作
                            }
                            //库存附表的操作
                            if (Db::name('stock_data')->where(array("cid"=>$cid,"shopid"=>$v['id'],"bcp"=>$infos['bcp']))->find()){
                                Db::name('stock_data')->where(array("cid"=>$cid,"shopid"=>$v['id'],"bcp"=>$infos['bcp']))->setInc('num', $v['num']); ;

                            }else{
                                Db::name('stock_data')->insert(array(
                                    'shopid'=>$v['id'],
                                    'num'=>$v['num'],
                                    'bcp'=>$infos['bcp'],
                                    'cid'=>$cid
                                ));
                            }

                        }else{
                            break;
                        }
                }
                //循环结束
                $this->success('操作成功');



            }else{
                $this->error("必须选择商品");
            }
            if ($params) {

            }

        }
        return $this->view->fetch();
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //add_stock(1,170,2,1);
        if ($this->userid!=1){
            $db = new \app\admin\model\Githouse();
            $info = $db->where(array('manger'=>$this->userid))->find();
            if (!$info)$this->error("您不是仓库管理员");
        }else{
            $db = new \app\admin\model\Githouse();
            $this->assign("data",$db->select());

        }
        //$this->error("暂无权限");

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            if ($this->userid!=1){
                list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null,array('cid'=>$info['id']));

            }else{
                list($where, $sort, $order, $offset, $limit) = $this->buildparams(null,null);

            }

            $total = $this->model
                ->where($where)
                ->group('order_id')
                ->count();

            $list = $this->model
                ->where($where)
                ->group('order_id')

                ->order('id desc')
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        //new Githouse();

        return $this->view->fetch();
    }
    public function view($ids){
       $ids = intval($ids);
       $info = $this->model->find($ids);
       $order_id = $info['order_id'];

        $list = Db::name('house_in')->where(array("order_id"=>$order_id))->paginate(10, false, ['query' => request()->param()]);

        $this->assign('list', $list);

        return $this->fetch();


    }
    protected function buildparams($searchfields = null, $relationSearch = null,$mer=array())
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", "id");
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset", 0);
        $limit = $this->request->get("limit", 0);
        $filter = (array)json_decode($filter, TRUE);
        $op = (array)json_decode($op, TRUE);
        $filter = $filter ? $filter : [];
        if ($mer){
            $filter = array_merge($mer,$filter);
        }
        $where = [];
        $tableName = '';
        if ($relationSearch) {
            if (!empty($this->model)) {
                $name = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
                $tableName = $name . '.';
            }
            $sortArr = explode(',', $sort);
            foreach ($sortArr as $index => & $item) {
                $item = stripos($item, ".") === false ? $tableName . trim($item) : $item;
            }
            unset($item);
            $sort = implode(',', $sortArr);
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$tableName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $tableName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        foreach ($filter as $k => $v) {
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $tableName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            switch ($sym) {
                case '=':
                case '!=':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                    $where[] = "FIND_IN_SET('{$v}', " . ($this->relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ")";
                    break;
                case 'FIND_IN_SET':
                    $where[] = "FIND_IN_SET( " . ($this->relationSearch ? $k : '`' . str_replace('.', '`.`', $k) . '`') . ",'{$v}')";
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr))
                        continue;
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } else if ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' time', $arr];
                    break;
                case 'LIKE':
                case 'LIKE %...%':
                    $where[] = [$k, 'LIKE', "%{$v}%"];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
        }
        $where = function ($query) use ($where) {
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit];
    }


}
